package badword

import "hytx_media/models"

type node struct {
	next  [256]*node
	isEnd bool
}

var root = &node{}

func addWord(n *node, word string) {
	for i := 0; i < len(word); i++ {
		if n.next[word[i]] == nil {
			n.next[word[i]] = &node{}
		}
		n = n.next[word[i]]
	}
	n.isEnd = true
}

func load() {
	var words []string = loadFrom()
	for _, word := range words {
		addWord(root, word)
	}
}

func Find(s string) (result []string) {
	load()
	for i := 0; i < len(s); i++ {
		for j, n := i, root; j < len(s) && n.next[s[j]] != nil; j++ {
			n = n.next[s[j]]
			if n.isEnd {
				result = append(result, s[i:j+1])
			}
		}
	}
	return result
}

func loadFrom() []string {
	var res []string

	models.DB.Table("sensitive").Pluck("keyword", &res)

	return res
}
